package com.le.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUtils {


    /**
     * 获取不带扩展名的文件名
     * @param fileName
     * @return
     */
    public static String getFileNameRemoveSuffix(String fileName) {
        int pos = fileName.lastIndexOf(".");
        if (pos > 0) {
            return fileName.substring(0, pos);
        }
        return fileName;
    }

    /**
     * 递归删除指定目录及其内容。
     *
     * @param directory 要删除的目录
     */
    public static void deleteDirectory(File directory) {
        File[] allContents = directory.listFiles();
        if (allContents != null) {
            for (File file : allContents) {
                deleteDirectory(file);
            }
        }
        directory.delete();
    }

    /**
     * 将指定目录中的图像压缩为zip文件，并将其写入输出流中。
     *
     * @param directory     包含图像文件的目录
     * @param outputStream  要写入zip文件的输出流
     * @throws IOException 如果发生I/O错误
     */
    public static void zipImages(File directory, OutputStream outputStream) throws IOException {
        try (ZipOutputStream zipOut = new ZipOutputStream(outputStream)) {
            File[] imageFiles = directory.listFiles();
            if (imageFiles != null) {
                for (File imageFile : imageFiles) {
                    ZipEntry zipEntry = new ZipEntry(imageFile.getName());
                    zipOut.putNextEntry(zipEntry);
                    try (FileInputStream fis = new FileInputStream(imageFile)) {
                        byte[] bytes = new byte[1024];
                        int length;
                        while ((length = fis.read(bytes)) >= 0) {
                            zipOut.write(bytes, 0, length);
                        }
                    }
                }
            }
        }
    }

    /**
     * 创建临时文件
     * @return
     * @throws IOException
     */
    public static File createTempDirectory() throws IOException {
        File tempDir = File.createTempFile("temp", Long.toString(System.nanoTime()));
        if (!tempDir.delete() || !tempDir.mkdir()) {
            throw new IOException("Could not create temp directory: " + tempDir);
        }
        return tempDir;
    }
}
